package com.sd.repay.controller;

import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.pojo.Balance;
import com.sd.repay.service.BalanceOperService;
import com.sd.repay.utils.JsonUtil;
import com.sd.repay.utils.StringUtil;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Map;

/**
 * Created by sd on 2018/08/21
 * 技术隐藏调用接口
 */
@Controller
@RequestMapping(value = "/hideCallMgr")
public class HideCallController {

    private static final Logger log = LoggerFactory.getLogger(HideCallController.class);

    @Autowired
    private BalanceOperService balanceOperService;

    /**
     * 用户调账
     *
     * @return
     */
    @RequestMapping(value = "/merAdjust", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult merAdjust(@RequestParam Map<String, String> params) {

        log.info("调账参数：" + params);
        String operator = params.get("operator");
        String amount = params.get("amount");
        String merNo = params.get("merNo");
        String merType = params.get("merType");
        String transType = params.get("transType");
        String balanceType = params.get("balanceType");
        String remark = params.get("remark");
        String balanceChannel = params.get("balanceChannel");
        String encryptTotalBalance = params.get("encryptTotalBalance");

        try {

            if (StringUtil.isBlank(operator, amount, merNo, merType, transType, balanceType, remark, balanceChannel)) {
                return CommonResult.build(403, "必要参数不能为空");
            }

            if (!Constants.MER_TYPE_MERCHANT.equals(merType) && !Constants.MER_TYPE_AGENT.equals(merType) && !Constants.MER_TYPE_PLAT.equals(merType)) {
                return CommonResult.build(403, "参数不合法");
            }
            if (!Constants.BALANCE_HIS_TRANS_TYPE_IN.equals(transType) && !Constants.BALANCE_HIS_TRANS_TYPE_OUT.equals(transType)) {
                return CommonResult.build(403, "参数不合法");
            }
            if (!Constants.BALANCE_HIS_TYPE_CURR.equals(balanceType) && !Constants.BALANCE_HIS_TYPE_HIS.equals(balanceType)
                    && !Constants.BALANCE_HIS_TYPE_FREEZE.equals(balanceType)) {
                return CommonResult.build(403, "参数不合法");
            }

            Balance balance = balanceOperService.getAccountByMerAndChannel(merNo, merType, balanceChannel);
            if (null != balance) {
                if (StringUtils.isBlank(encryptTotalBalance)) {
                    return CommonResult.build(403, "必要参数不能为空");
                }
                String sqlEncryptTotalBalance = balance.getEncryptTotalBalance();
                if (!encryptTotalBalance.equals(sqlEncryptTotalBalance)) {
                    return CommonResult.build(403, "金额校验异常");
                }
            }

            BigDecimal amountBig = new BigDecimal(amount);
            String balanceRemark = operator + "发起调账：【" + remark + "】";

            CommonResult balanceRes = balanceOperService.updateBalance(merNo, merType, amountBig, transType, balanceType,
                    Constants.BALANCE_HIS_SERVICE_ADJUST, String.valueOf(System.currentTimeMillis()), balanceRemark, balanceChannel);
            //记录日志
            WebUtil.saveOperateLog(operator, "ADJUST", "t_balance", JsonUtil.objectToJson(params), null, balanceRemark);
            return balanceRes;
        } catch (Exception e) {
            log.error("调账失败", e);
            return CommonResult.build(403, "调账失败，请稍候再试");
        }
    }

    /**
     * 用户余额冻结
     *
     * @return
     */
    @RequestMapping(value = "/freeze", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult freeze(@RequestParam Map<String, String> params) {

        log.info("冻结参数：" + params);
        String operator = params.get("operator");
        String amount = params.get("amount");
        String merNo = params.get("merNo");
        String merType = params.get("merType");
        String remark = params.get("remark");
        String balanceChannel = params.get("balanceChannel");
        String encryptTotalBalance = params.get("encryptTotalBalance");

        try {

            if (StringUtil.isBlank(operator, amount, merNo, merType, remark, balanceChannel, encryptTotalBalance)) {
                return CommonResult.build(403, "必要参数不能为空");
            }
            if (!Constants.MER_TYPE_MERCHANT.equals(merType) && !Constants.MER_TYPE_AGENT.equals(merType) && !Constants.MER_TYPE_PLAT.equals(merType)) {
                return CommonResult.build(403, "参数不合法");
            }

            Balance balance = balanceOperService.getAccountByMerAndChannel(merNo, merType, balanceChannel);
            if (null == balance) {
                return CommonResult.build(403, "通道账户为空");
            }
            String sqlEncryptTotalBalance = balance.getEncryptTotalBalance();
            if (!encryptTotalBalance.equals(sqlEncryptTotalBalance)) {
                return CommonResult.build(403, "金额校验异常");
            }
            BigDecimal amountBig = new BigDecimal(amount);
            int count = balanceOperService.freezeBalance(merNo, merType, amountBig, balanceChannel);
            String logMsg = String.format("商户类型【{}】商户编号【{}】冻结渠道【{}】金额【{}】影响的行数【{】】", new Object[]{merType, merNo, balanceChannel, amountBig, count});
            log.info(logMsg);
            if (count > 0) {
                //记录日志
                WebUtil.saveOperateLog(operator, "FREEZE", "t_balance", JsonUtil.objectToJson(params), null, logMsg);
            }
            return CommonResult.ok();
        } catch (Exception e) {
            log.error("冻结失败", e);
            return CommonResult.build(403, "冻结失败，请稍候再试");
        }
    }

    /**
     * 用户余额解冻
     *
     * @return
     */
    @RequestMapping(value = "/unfreeze", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult unfreeze(@RequestParam Map<String, String> params) {

        log.info("解冻参数：" + params);
        String operator = params.get("operator");
        String merNo = params.get("merNo");
        String merType = params.get("merType");
        String remark = params.get("remark");
        String balanceChannel = params.get("balanceChannel");
        String encryptTotalBalance = params.get("encryptTotalBalance");

        try {

            if (StringUtil.isBlank(operator, merNo, merType, remark, balanceChannel, encryptTotalBalance)) {
                return CommonResult.build(403, "必要参数不能为空");
            }
            if (!Constants.MER_TYPE_MERCHANT.equals(merType) && !Constants.MER_TYPE_AGENT.equals(merType) && !Constants.MER_TYPE_PLAT.equals(merType)) {
                return CommonResult.build(403, "参数不合法");
            }

            Balance balance = balanceOperService.getAccountByMerAndChannel(merNo, merType, balanceChannel);
            if (null == balance) {
                return CommonResult.build(403, "通道账户为空");
            }
            String sqlEncryptTotalBalance = balance.getEncryptTotalBalance();
            if (!encryptTotalBalance.equals(sqlEncryptTotalBalance)) {
                return CommonResult.build(403, "金额校验异常");
            }
            BigDecimal freezeAmount = balance.getFreezeBalance();
            if (freezeAmount.compareTo(BigDecimal.ZERO) <= 0) {
                return CommonResult.build(403, "该通道账户非冻结状态");
            }
            int count = balanceOperService.unfreezeBalance(merNo, merType, balanceChannel);
            String logMsg = String.format("商户类型【{}】商户编号【{}】解冻渠道【{}】影响的行数【{】】", new Object[]{merType, merNo, balanceChannel, count});
            log.info(logMsg);
            if (count > 0) {
                //记录日志
                WebUtil.saveOperateLog(operator, "UNFREEZE", "t_balance", JsonUtil.objectToJson(params), null, logMsg);
            }
            return CommonResult.ok();
        } catch (Exception e) {
            log.error("解冻失败", e);
            return CommonResult.build(403, "解冻失败，请稍候再试");
        }
    }
}
